<?php
	///////////////////////////////////////////////////////////////////////////////////////////////////
	//	TIMESHEET
	//	WRITTEN BY: TRAVIS THORNTON
	//	12-07-2009
	//
	//	What this page does:
	//	1) Shows a timesheet for a user (managers can see their employee's timesheets)
	//	2) Allows errors to be submitted
	//	3) Shows total hour counts
	//
	////////////////////////////////////////////////////////////////////////////////////////////////////
	
	session_start();
	require_once 'php_includes.php';

	//Make sure logged in
	checkLogin();

	//if there is a session, then it was set from an error report. this is to guide it to the correct timesheet
	if(isset($_SESSION['usertime']) && isset($_SESSION['period']))
	{
		$_POST['usertime'] = $_SESSION['usertime'];//set the posts so they can be used
		$_POST['period'] = $_SESSION['period'];
		unset($_SESSION['usertime']);//unset the session vars
		unset($_SESSION['period']);
	}
	
	//if no input
	if(!$_POST['usertime'] || !$_POST['period'])
	{
		//if no input user, use the logged in user as the id
		$user = $_SESSION['tmsUserID'];
		if(!$_POST['period'])
		{
			$period_start = 0;//will use current timesheet
		}
		else
		{
			$period_start = $_POST['period'];//will use passed in timesheet
		}
	}else{
		$user = $_POST['usertime'];//will use passed in timesheet and user
		$period_start = $_POST['period'];
	}

	require_once 'time_functions.php';

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Payroll and Timesheet Management Website</title>
    <link rel="stylesheet" type="text/css" href="styles.css" />

    <script type="text/javascript" src="jsfunctions.js">
    </script>

  </head>
  <body>
    
	<?php writeHeader(); ?>
	
   <?php	
	sqlConnect();		
	
	//Get the data for this period
	if($period_start != 0)
	{
		$sql = 'select Entry1, Entry2, Entry3, Entry4, Entry5, Entry6, Entry7, Entry8, Entry9, Entry10, Entry11, Entry12, Entry13, Entry14, PeriodStart, PeriodEnd, ManagerID, EmployeeFName, EmployeeLName, PeriodStatus  from PayPeriod, Employee where Employee.EmployeeID = PayPeriod.EmployeeID AND PayPeriod.EmployeeID = \'' . $user . '\' AND PeriodStart LIKE(\'' . $period_start . '\')';
	}
	else//use current timesheet(if avail
	{
		$sql = 'select Entry1, Entry2, Entry3, Entry4, Entry5, Entry6, Entry7, Entry8, Entry9, Entry10, Entry11, Entry12, Entry13, Entry14, PeriodStart, PeriodEnd, ManagerID, EmployeeFName, EmployeeLName, PeriodStatus  from PayPeriod, Employee where Employee.EmployeeID = PayPeriod.EmployeeID AND PayPeriod.EmployeeID = \'' . $user . '\' AND PeriodStatus = 0';
	}
	
	// Perform Query
	$sqlresult = sqlQuery($sql);
	
	//see if it is a manager for the employee
    $manager = 0;
    $sql = "SELECT ManagerID FROM Employee WHERE EmployeeID = '" . $user . "'";  
    $results = sqlQueryNoLog($sql);
    sqlExit();
        
	//set manager var 
    if(mysql_result($results, 0, 0) == $_SESSION['tmsUserID'])
    {
        $manager = 1;
    }

	
	// if it is a different user, make sure that the manager is looking at it.
	if($user != $_SESSION['tmsUserID'])
	{
		if(mysql_result($sqlresult, 0, 16) != $_SESSION['tmsUserID'])
		{
			die ("You do not have permission to be here.");
		}
	}
	
	//if there was no result, show error
	if(mysql_num_rows($sqlresult) == 0)
	{
		echo "There is no current timesheet for you. Did you submit your timesheet already?";
	}
	else
	{
		//get the day events put into a 2d array, $day
		$day[0] = explode("|", mysql_result($sqlresult, 0, 0));
		$day[1] = explode("|", mysql_result($sqlresult, 0, 1));
		$day[2] = explode("|", mysql_result($sqlresult, 0, 2));
		$day[3] = explode("|", mysql_result($sqlresult, 0, 3));
		$day[4] = explode("|", mysql_result($sqlresult, 0, 4));
		$day[5] = explode("|", mysql_result($sqlresult, 0, 5));
		$day[6] = explode("|", mysql_result($sqlresult, 0, 6));
		$day[7] = explode("|", mysql_result($sqlresult, 0, 7));
		$day[8] = explode("|", mysql_result($sqlresult, 0, 8));
		$day[9] = explode("|", mysql_result($sqlresult, 0, 9));
		$day[10] = explode("|", mysql_result($sqlresult, 0, 10));
		$day[11] = explode("|", mysql_result($sqlresult, 0, 11));
		$day[12] = explode("|", mysql_result($sqlresult, 0, 12));
		$day[13] = explode("|", mysql_result($sqlresult, 0, 13));
		
		
		//We need to calculate the max events for one day and use that as a guide where to place stuff in the table
		//first week
		$max_events[0] = 0;
		$has_extra[0] = 0;
		for($n = 0; $n < 7; ++$n)
		{
			//see if it is the max
			if((count($day[$n]) > count($day[$max_events[0]]) )|| ($day[$max_events[0]] == "" && $day[$n] != ""))
			{
				//set it
				$max_events[0] = $n;
			}
			
			//determin if it has bonus time
			for($i = 0; $i < count($day[$n]); ++$i)
			{	
				$data = explode("@", $day[$n][$i]);
				if($data[0] == "4" && ((int)$data[1]>0))
				{//yes it does, and it is > 0
					$has_extra[0] = 1;
				}
			}
		}
		
		//2nd week
		//split up because it may have a differnt entry with more or less events than the max for week 1
		$max_events[1] = 7;
		$has_extra[1] = 0;
		for($n = 7; $n < 14; ++$n)
		{
			//see if it is the max
			if((count($day[$n]) > count($day[$max_events[1]]) )|| ($day[$max_events[1]] == "" && $day[$n] != ""))
			{
				$max_events[1] = $n;//set it
			}
				
			//see if it has bonus time
			for($i = 0; $i < count($day[$n]); ++$i)
			{
				$data = explode("@", $day[$n][$i]);
				if($data[0] == "4" && ((int)$data[1]>0))
				{
					$has_extra[1] = 1;//it does
				}
			}
		}
		
		//arraify the dates
		$date1 = explode("-", mysql_result($sqlresult, 0, 14));
		$date2 = explode("-", mysql_result($sqlresult, 0, 15));
		$string = $date1[1] . "/" . $date1[2] . "/" . $date1[0];
		$date_header[0] = strtotime($string);
		$date_header[1] = strtotime($string . " + 1 week");// get a week ahead - just adding the seconds would repeat sunday 11.01.2009 
		
		//now for table
		echo "<p>\n";
		echo "<span class=\"pageheader\">";

		//display user if manager logged in 
		if($user != $_SESSION['tmsUserID'])
		{
			echo mysql_result($sqlresult, 0, 17) . " " . mysql_result($sqlresult, 0, 18) . " (" . $user . ")'s ";
		}
		else
		{
			echo "My ";
		}
		
		///Submit or approve buttons
		if(mysql_result($sqlresult, 0, 19) != 0)
		{
			echo "Timesheet for pay period: ";
			echo $date1[1] . "/" . $date1[2] . "/" . $date1[0] . " - " . $date2[1] . "/" . $date2[2] . "/" . $date2[0] . "</span><br/>\n";
		}
		else
		{
			echo "Current Timesheet</span><br/>\n";
		}
		
		echo "</p>\n";
		
		//if current, show the submit timesheet button
		if(mysql_result($sqlresult, 0, 19) == 0)
		{
			echo "<form action=\"submittime.php\" method=\"post\" target=\"submit_time\" onSubmit=\"window.open('', 'submit_time', 'width=450,height=300,status=yes,resizable=yes,scrollbars=yes')\">";
			echo "<div class=\"center\">";
			echo "<input type=\"hidden\" name=\"action\"value=\"submit\" />";
			echo "<input type=\"hidden\" name=\"usertime\"value=\"" . $user . "\" />";
			echo "<input type=\"hidden\" name=\"period\"value=\"" . mysql_result($sqlresult, 0, 14) . "\" />"; 
			echo "<input type=\"submit\" value=\"Submit Time\" class=\"button\" />";
			echo "</div></form>"; 
		}
		else if(mysql_result($sqlresult, 0, 19) == 1)//show approve if waiting for approval and logged in as manager
		{
			if(mysql_result($sqlresult, 0, 16) == $_SESSION['tmsUserID'])
			{
				echo "<form action=\"submittedtime.php\" method=\"post\">";
				echo "<div class=\"center\">";
				echo "<input type=\"hidden\" name=\"action\"value=\"approve\" />";
				echo "<input type=\"hidden\" name=\"usertime\"value=\"" . $user . "\" />";
				echo "<input type=\"hidden\" name=\"period\"value=\"" . mysql_result($sqlresult, 0, 14) . "\" />"; 
				echo "<input type=\"submit\" value=\"Approve Time\" class=\"button\" />";
				echo "</div></form>";
			}
		}
		///
		
		echo "<div>\n";
		
		//Pay periods
		for($y = 0; $y < 2; ++$y)
		{
			$odd = 1;
			echo "<table class=\"master\">\n";
			echo "<tr class=\"odd\">\n";
			echo "<th></th>\n";
			
			//write the date headers
			for($i = 0; $i < 7; ++$i)
			{
				echo "<th class=\"pad\">";
				echo date("D m/d/y", $date_header[$y]);
				echo "</th>\n";
				
				$date_header[$y] += 86400;
			}
			echo "</tr>\n";
			//end date headers
			
			//track last event written
			$last_event[0] = 0;
			$last_event[1] = 0;
			$last_event[2] = 0;
			$last_event[3] = 0;
			$last_event[4] = 0;
			$last_event[5] = 0;
			$last_event[6] = 0;
			
			//display the event times
			for($n = 0; $n < count($day[$max_events[$y]]); ++$n)
			{
				//only if it has data
				if($day[$max_events[$y]][0] != "")
				{
					//Find event type for this row
					$max_data = explode( "@", $day[$max_events[$y]][$n]);
					if($max_data[0] != "4")
					{
						if($odd == 1)
						{
							$odd = 0;
							echo "<tr class=\"even\">\n";
						}
						else
						{
							$odd = 1;
							echo "<tr class=\"odd\">\n";
						}
						
						echo "<td>";
						
						//write the event in the max data array
						switch($max_data[0])
						{
							case "0":
								echo "Clock In";
							break;
							
							case "1":
								echo "Clock Out";
							break;
							
							case "2":
								echo "Going to Lunch";
							break;
							
							case "3":
								echo "Back From Lunch";
							break;

							default:
								echo"Error";
						}
						
						echo "</td>";
					
					}	
					//for each day on this row
						for($i = 0; $i < 7; ++$i)
						{
							//extract date
							$day_data = explode( "@", $day[($i + (7 * $y))][$last_event[$i]]);
							
							if($day_data[0] == "4")//ignore 4 for now
							{
								$last_event[$i] = $n+1;//move to next day
							}
							else
							{
								$has_err_reported = 0; // to show red bg if there is an error reported for it
								
								//need to see if there was an error reported on this event
								sqlConnect();
								$sql = "SELECT CorrectionEvent FROM ReportedErrors, Employee WHERE Employee.EmployeeID = ReportedErrors.EmployeeID AND EntryNo=". ($i + (7*$y)) ." AND CorrectionTimestamp='".$day[($i + (7 * $y))][$last_event[$i]]."'";
								$results = sqlQuery($sql);
								$num_rows = mysql_num_rows($results);
								sqlExit();
								
								//check num rows
								if($num_rows > 0) { $has_err_reported = 1; }
								
								//if error show red bg
								if($has_err_reported == 1)
								{
									echo "<td class=\"pad_err\">";
								}
								else
								{
									echo "<td class=\"pad\">";
								}
								
								//users can report errors on current time
								if(mysql_result($sqlresult, 0, 19) == 0 || (mysql_result($sqlresult, 0, 19) == 1 && $manager==1))
								{
									echo " <form action=\"reporterror.php\" method=\"post\" target=\"newwin\" onSubmit=\"window.open('', 'newwin', 'width=450,height=350,status=yes,resizable=yes,scrollbars=yes')\">";
								}	
								if($day_data[0] == $max_data[0])
								{	
									//extract date data and turn it in to 12hr
									$date = explode(" ", $day_data[1]);
									$time = explode(":", $date[1]);
									$hour = (int)$time[0];
									$period = "AM";
									
									if($time[0] == 12)
									{
										$period = "PM";
									}
									else if($time[0] > 12)
									{
										$hour = $hour - 12;
										$period = "PM";
									}
									
									//show time
									echo $hour . ":" . $time[1] . " " . $period . "&nbsp;";
									
									//show correction form if current for user, or if pending for manager
									if(mysql_result($sqlresult, 0, 19) == 0 || (mysql_result($sqlresult, 0, 19) == 1 && $manager==1))
									{
										//show form
										echo "<input type=\"image\" class=\"editbutton\" src=\"error.png\" HEIGHT=\"20\" WIDTH=\"20\" alt=\"Report Error\"/>";
										echo "<input type=\"hidden\" name=\"usertime\"value=\"" . $user . "\" />";
										echo "<input type=\"hidden\" name=\"period\"value=\"" . mysql_result($sqlresult, 0, 14) . "\" />"; 
										echo "<input type=\"hidden\" name=\"action\"value=\"submit_error\" />";
										echo "<input type=\"hidden\" name=\"offset\" value=\"". (($i + (7*$y))+1) ."\"/>";
										echo "<input type=\"hidden\" name=\"timestamp\" value=\"". ($day[($i + (7 * $y))][$last_event[$i]]) ."\"/>";
										echo "</form>";
									}
									
									//move event down
									$last_event[$i] = $n+1;
								}
								
								
							}
							
							echo "</td>";
						}
						
						echo "</tr>\n";
				
				}
			}
			//end event times
			
			//extra time only if it has extra time on this week or it is a manager
			if($has_extra[$y] == 1 || $manager ==1)
			{
				if($odd == 1)
				{
					$odd = 0;
					echo "<tr class=\"even\">\n";
				}
				else
				{
					$odd = 1;
					echo "<tr class=\"odd\">\n";
				}
				
				echo "<td>Bonus Time:</td>\n";
				
				for($i = 0; $i < 7; ++$i)
				{
					echo "<td class=\"pad\">";
					
					//see if there is extra time for this day
					for($u = 0; $u < count($day[$i + (7 * $y)]); ++$u)
					{
						//extract
						$day_data = explode( "@", $day[$i + (7 * $y)][$u]);

						//if it is >0 and a user or if it is a manager, display it
						if($day_data[0] == "4" && ((int)$day_data[1]>0 || $manager == 1))
						{	
							//manager can edit this on current and pending timesheets
							if($manager == 1 && (mysql_result($sqlresult, 0, 19) == 1 || mysql_result($sqlresult, 0, 19) == 0))
							{
								echo " <form action=\"reporterror.php\" method=\"post\" target=\"newwin\" onSubmit=\"window.open('', 'newwin', 'width=450,height=350,status=yes,resizable=yes,scrollbars=yes')\">";
							}
							
							//calc bonus time
							$bonus_time = ($day_data[1] / 60);
							
							//print it and round
							echo round($bonus_time, 2) . " Hour";
							
							//plural
							if($bonus_time != 1)
							{
								echo "s";
							}
							
							//space
							echo " &nbsp;";
							
							//manager can edit this on current and pending timesheets
							if($manager == 1 && (mysql_result($sqlresult, 0, 19) == 1 || mysql_result($sqlresult, 0, 19) == 0))
							{
								//correction form
								echo "<input type=\"image\" src=\"error.png\" class=\"editbutton\" HEIGHT=\"20\" WIDTH=\"20\" alt=\"Change Value\"/>";
								echo "<input type=\"hidden\" name=\"usertime\"value=\"" . $user . "\" />";
								echo "<input type=\"hidden\" name=\"period\"value=\"" . mysql_result($sqlresult, 0, 14) . "\" />"; 
								echo "<input type=\"hidden\" name=\"action\"value=\"changebonus\" />";
								echo "<input type=\"hidden\" name=\"offset\" value=\"". (($i + (7*$y))+1) ."\"/>";
								echo "<input type=\"hidden\" name=\"bon\" value=\"". ($day[$i + (7 * $y)][$u]) ."\"/></form>";
							}
						}
					}			
					echo "</td>\n";
				}
				echo "</tr>\n";
			}
			//end extra
			
			//add event is only for managers
			//it allows them to add an event only to current or pending timesheets at the end. this may mean deleting other events in order to place it right
			if($manager ==1)
			{
				if($odd == 1)
				{
					$odd = 0;
					echo "<tr class=\"even\">\n";
				}
				else
				{
					$odd = 1;
					echo "<tr class=\"odd\">\n";
				}
				
				echo "<td>Add Event:</td>\n";
				
				//per day
				for($i = 0; $i < 7; ++$i)
				{
					echo "<td class=\"pad\">";
					
					//put the form is current or pending only
					if($manager == 1 && (mysql_result($sqlresult, 0, 19) == 1 || mysql_result($sqlresult, 0, 19) == 0))
					{
						echo " <form action=\"reporterror.php\" method=\"post\" target=\"newwin\" onSubmit=\"window.open('', 'newwin', 'width=450,height=350,status=yes,resizable=yes,scrollbars=yes')\">";
						echo "<input type=\"submit\" value=\"Add Event\" class=\"button\" />";
						echo "<input type=\"hidden\" name=\"usertime\"value=\"" . $user . "\" />";
						echo "<input type=\"hidden\" name=\"period\"value=\"" . mysql_result($sqlresult, 0, 14) . "\" />"; 
						echo "<input type=\"hidden\" name=\"action\"value=\"addevent\" />";
						echo "<input type=\"hidden\" name=\"offset\" value=\"". (($i + (7*$y))+1) ."\"/>";
						echo "</form>";
					}		
					echo "</td>\n";
				}
					
				echo "</tr>\n";
			}
			//end extra event
			
			//totals for the period:
			if($odd == 1)
			{
				$odd = 0;
				echo "<tr class=\"even\">\n";
			}
			else
			{
				$odd = 1;
				echo "<tr class=\"odd\">\n";
			}
			
			echo "<td>Total:</td>\n";
			
			for($i = 0; $i < 7; ++$i)
			{
				//gets total time for the day
				echo "<td class=\"pad_top\">";
				echo getTotals($day[$i + (7 * $y)]);
				echo "</td>\n";
			}
					
			echo "</tr>\n";
			//end totals
			
			echo "</table>\n";
			echo "</div>\n";	
		}
		//end for loop for the 2 weeks
		
		//time totals
		echo "<div class=\"center\">\n";
		echo "<br />\n";
		echo "  <span class=\"underline\">Totals for this pay period:</span>\n";
		echo "  <br/>\n";
		echo "  <div>\n";
		echo "  <span class=\"bold_pad\">\n";
		echo "    Regular\n";
		echo "  </span>\n";
		echo "  <span class=\"italic\">\n";
		echo "    " . $total_hours . " hours\n";
		echo "  </span>\n";
		echo "  <br/>\n";
		if($total_ot > 0)//only if needed
		{
			echo "  <span class=\"bold_pad\">\n";
			echo "    Overtime\n";
			echo "  </span>\n";
			echo "  <span class=\"italic\">\n";
			echo "    " . $total_ot . " hours\n";
			echo "  </span>\n";
			echo "  <br/>\n";
		}
		
		if($total_double > 0)//only if needed
		{
			echo "  <span class=\"bold_pad\">\n";
			echo "    Double Time\n";
			echo "  </span>\n";
			echo "  <span class=\"italic\">\n";
			echo "    " . $total_double . " hours\n";
			echo "  </span>\n";
			echo "  <br/>\n";
		}
		if($total_bonus > 0)//only if needed
		{
			echo "  <span class=\"bold_pad\">\n";
			echo "    Bonus Time\n";
			echo "  </span>\n";
			echo "  <span class=\"italic\">\n";
			echo "    " . $total_bonus . " hours\n";
			echo "  </span>\n";
		}
		echo "  </div>\n";
		echo "</div>\n";
	}
   ?> 
  </body>
</html>
